package com.zretc.baiDuFace;

import java.util.Map;

import javax.imageio.ImageIO;

import com.zretc.util.HttpUtil;
import com.zretc.util.Base64Util;
import com.zretc.util.GsonUtils;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 人脸检测与属性分析
 */
public class UpdateFace {

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String updatePerson(String uri) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update";

        //Base64转化
        File image = new File(uri);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String Base64 = null;
        try {
            BufferedImage img = ImageIO.read(image);
            ImageIO.write(img, "jpg", out);
            byte[] bytes = out.toByteArray();
            Base64 = Base64Util.encode(bytes);
        } catch (IOException e1) {
            e1.printStackTrace();
        }


        //https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595091979951&di=17e311df3305b3f7709cad7454830aef&imgtype=0&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D871782970%2C4175753760%26fm%3D214%26gp%3D0.jpg
        try {//https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1595093130273&di=de3c906a19e1e007f275a4d5dec5cbee&imgtype=0&src=http%3A%2F%2Fimages.china.cn%2Fattachement%2Fjpg%2Fsite1000%2F20170424%2F7427ea210a2c1a677cda59.jpg


            Map<String, Object> map = new HashMap<>();
            map.put("image", Base64);
            map.put("group_id", "faceLogin");
            map.put("user_id", "0001");
            map.put("liveness_control", "NORMAL");
            map.put("image_type", "BASE64");
            map.put("quality_control", "LOW");
            map.put("action_type", "REPLACE");

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.810201ae6dcaa18b5376db6258eb9e42.2592000.1597653190.282335-21458214";
            //巧玲d131f3d7ddc6da54493e5ac6e0a2fb48

            String result = HttpUtil.post(url, accessToken, "application/json", param);
            System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String uri = "E:/20200405/test/meglass.jpg";
        String faceDetect = UpdateFace.updatePerson(uri);


    }

}
